package top.ljlgithub.api.controller;

import com.mysql.jdbc.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.ljlgithub.api.bean.*;
import top.ljlgithub.api.common.response.Meta;
import top.ljlgithub.api.common.response.ResponseEntity;
import top.ljlgithub.api.exception.ParamException;
import top.ljlgithub.api.exception.RightException;
import top.ljlgithub.api.jwt.JwtUtils;
import top.ljlgithub.api.service.ManagerService;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName
 * @Description TODO
 * @Author L1470
 * @Date 2021/4/25 19:31
 * @Version 1.0
 **/
@RestController
@CrossOrigin
public class ManagerController {
    @Autowired
    ManagerService managerService;

    @RequiresPermissions("user:createManager:*")
    @PostMapping("/register")
    public ResponseEntity register(@RequestBody UsernameAndPassword usernameAndPassword) throws ParamException {
        String username = usernameAndPassword.getUsername();
        String password = usernameAndPassword.getPassword();

        if (StringUtils.isNullOrEmpty(username) || StringUtils.isNullOrEmpty(password)){
            throw new ParamException();
        }
        Manager manager = new Manager();
        manager.setUsername(username);
        manager.setPwd(password);
        manager.setRole_id(0);
        managerService.register(manager);
        Meta meta = new Meta("注册成功", 200);
        //服务器的异常由SpringBoot自动以json格式返回
        return new ResponseEntity(null, meta);
    }

    //@CrossOrigin
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody UsernameAndPassword usernameAndPassword) {
        String username = usernameAndPassword.getUsername();
        String password = usernameAndPassword.getPassword();

        if (StringUtils.isNullOrEmpty(username) || StringUtils.isNullOrEmpty(password)){
            throw new IncorrectCredentialsException();
        }
        Manager manager = managerService.login(username, password);
        Map<String, String> map = new HashMap<>();
        map.put("id",manager.getId()+"");
        map.put("username",manager.getUsername());
        String sign = JwtUtils.sign(map);
        manager.setToken(sign);
        Meta meta = new Meta("登录成功", 200);
        ResponseEntity<Object> result = new ResponseEntity<>(manager, meta);
        return result;
    }

    @GetMapping("/logout")
    public ResponseEntity logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        Meta meta = new Meta("退出成功", 200);
        ResponseEntity<Object> result = new ResponseEntity<>(null,meta);
        return result;
    }


    @GetMapping("/test")
    @RequiresRoles("admin")
    public ResponseEntity test(){
        Meta meta = new Meta("授权测试", 200);
        return new ResponseEntity(null,meta);
    }

    @RequiresPermissions("user:createManager:*")
    @PostMapping("/users")
    public ResponseEntity addUser(@RequestBody AddUserParam addUserParam){
        String email = addUserParam.getEmail();
        String mobile = addUserParam.getMobile();
        String username = addUserParam.getUsername();
        String password = addUserParam.getPassword();
        Manager manager = new Manager(null,40,username,password,mobile,email,true,null,null);
        managerService.addUser(manager);
        Meta meta = new Meta("创建成功",201);
        ResponseEntity<Object> result = new ResponseEntity<>(manager,meta);
        return result;
    }

    @RequiresPermissions("user:updateManager:*")
    @PutMapping("/users/{uId}/state/{type}")
    public ResponseEntity updateUser(@PathVariable("uId") int uId,@PathVariable("type") boolean type) throws RightException {
        if (uId == 500){
            throw new RightException();
        }
        managerService.updateUser(uId, type);
        Meta meta = new Meta("设置状态成功",200);
        Manager manager = managerService.findUserById(uId);
        ResponseEntity<Object> result = new ResponseEntity<>(manager,meta);
        return result;
    }

    @RequiresPermissions("user:getManager:*")
    @GetMapping("/users/{id}")
    public ResponseEntity findUserById(@PathVariable("id") int id){
        Meta meta = new Meta("查询成功",200);
        Manager manager = managerService.findUserById(id);
        ResponseEntity<Object> result = new ResponseEntity<>(manager,meta);
        return result;
    }

    @RequiresPermissions("user:deleteManager:*")
    @DeleteMapping("/users/{id}")
    public ResponseEntity deleteUserById(@PathVariable("id") int id) throws RightException {
        if (id == 500){
            throw new RightException();
        }
        Meta meta = new Meta("删除成功",200);
        managerService.deleteUserById(id);
        ResponseEntity<Object> result = new ResponseEntity<>(null,meta);
        return result;
    }

    @RequiresPermissions("user:updateManager:*")
    @PutMapping("/users/{id}/role")
    public ResponseEntity updateUserRole(@PathVariable("id") int id, @RequestBody RidParam ridParam) throws RightException {
        if (id == 500){
            throw new RightException();
        }
        Meta meta = new Meta("设置角色成功",200);
        Integer rid = ridParam.getRid();
        managerService.updateUserRole(id,rid);
        Manager manager = managerService.findUserById(id);
        ResponseEntity<Object> result = new ResponseEntity<>(manager,meta);
        return result;
    }


    @RequiresPermissions("user:updateManager:*")
    @PutMapping("/users/{id}")
    public ResponseEntity updateUser(@RequestBody UserInfo userInfo, @PathVariable("id") Integer id) throws ParamException {
        Manager manager = new Manager();
        manager.setId(id);
        manager.setEmail(userInfo.getEmail());
        manager.setMobile(userInfo.getMobile());
        if (manager.getEmail() == null || manager.getMobile() == null){
            throw new ParamException();
        }
        Manager data = managerService.updateUserInfo(manager);
        Meta meta = new Meta("更新成功", 200);
        ResponseEntity<Object> result = new ResponseEntity<>(data,meta);
        return result;
    }
}
